﻿using net8.Helper;
using net8.Models.XiTong;
using System.Text;

namespace net8
{
    public static class AppExtensions
    {
        public static void LogHandle(this WebApplication app)
        {
            app.Use(async (context, next) =>
            {
                DateTime startTime = DateTime.Now;

                string url = context.Request.Path.ToString();
                string type = context.Request.Headers["User-Agent"];
                context.Request.EnableBuffering();//可以多次读取
                var reader = new StreamReader(context.Request.Body, Encoding.UTF8);
                string body = await reader.ReadToEndAsync();
                context.Request.Body.Seek(0, SeekOrigin.Begin);
                body = body.Replace("\0", "");
                body = body.Length > 4000 ? "" : body;
                Guid userId = Guid.Empty;
                if (context.User.Claims.Any(u => u.Type == "UserId"))
                {
                    userId = Guid.Parse(context.User.Claims.First(u => u.Type == "UserId").Value);
                }

                try
                {
                    await next();

                    DateTime endTime = DateTime.Now;

                    XTLog model = new XTLog()
                    {
                        Id = Guid.NewGuid(),
                        UserId = userId,
                        LogType = "请求记录",
                        StartTime = startTime,
                        EndTime = endTime,
                        BrowserType = type,
                        Durtion = (endTime - startTime).Milliseconds,
                        RequestUrl = url,
                        RequestBody = body,
                        ExceptionInfo = ""
                    };

                    LogHelper.Add(model);
                }
                catch (Exception ex)
                {
                    DateTime endTime = DateTime.Now;



                    XTLog model = new XTLog()
                    {
                        Id = Guid.NewGuid(),
                        UserId = userId,
                        LogType = "系统异常",
                        StartTime = startTime,
                        EndTime = endTime,
                        BrowserType = type,
                        Durtion = (endTime - startTime).Milliseconds,
                        RequestUrl = url,
                        RequestBody = body,
                        ExceptionInfo = ex.ToString()
                    };

                    LogHelper.Add(model);
                }
            });
        }
    }
}
